﻿namespace PomodoroTool
{
    #region

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Controls.Primitives;

    using Core;

    #endregion

    /// <summary>
    /// Interaction logic for Taskpad.xaml
    /// </summary>
    public partial class TaskpadWindow : Window
    {
        #region Constants and Fields

        public TaskpadPresenter Presenter;

        private Subject<object> _textChangedSubject;

        private Subject<object> _scrollSubject;

        #endregion

        #region Constructors and Destructors

        public TaskpadWindow()
        {
            InitializeComponent();

            var layoutUpdated = Observable.FromEvent<EventArgs>(txtTaskList, "LayoutUpdated");
            var textChanged = Observable.FromEvent<TextChangedEventArgs>(txtTaskList, "TextChanged");

            _scrollSubject = new Subject<object>();
            _textChangedSubject = new Subject<object>();

            Observable.Join(layoutUpdated.And(textChanged.Throttle(TimeSpan.FromMilliseconds(100))).Then<object>((x, y) => null))
                .Merge(_scrollSubject.Throttle(TimeSpan.FromMilliseconds(100)))
                .Merge(_textChangedSubject)
                .ObserveOnDispatcher()
                .Subscribe(UpdateTasksFromText);

        }

        void UpdateTasksFromText(object o)
        {
            var parser = new TaskFormatter();
            var tasks =  parser.ParseText(txtTaskList.Text);

            canvasLeftPanel.Children.Clear();
            int taskIndex = 0;
            foreach (var task in tasks)
            {
                var charIndex = txtTaskList.GetCharacterIndexFromLineIndex(task.LineFound);
                var rect = txtTaskList.GetRectFromCharacterIndex(charIndex);

                var taskControl = new TaskItem();
                taskControl.AddPomodoro(task.Pomodoros);
                if (task.Completed)
                {
                    taskControl.AddDone();
                }
                int index = taskIndex;
                taskControl.MyMouseUp += () => this.Presenter.OnTaskClick(index);

                Canvas.SetTop(taskControl, rect.Top);
                Canvas.SetLeft(taskControl, 0);

                canvasLeftPanel.Children.Add(taskControl);
                taskIndex++;
            }   
        }


        #endregion

        #region Properties

        public IEnumerable<PomodoroController.Task> Tasks
        {
            get
            {
                return new TaskFormatter().ParseText(txtTaskList.Text);
            }
            set
            {
                txtTaskList.Text = new TaskFormatter().FormatTasks(value);
                _textChangedSubject.OnNext(null);
            }
        }

        
        #endregion

        #region Methods

        #endregion

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.Presenter.OnClosing();
        }

        private void txtTaskList_Scroll(object sender, ScrollEventArgs e)
        {
            _scrollSubject.OnNext(null);

        }
    }

    public class TaskpadPresenter
    {
        #region Constants and Fields

        private readonly PomodoroController _pomodoroController;

        private readonly TaskpadWindow _view;

        public event Action TaskpadClosing = delegate { };

        private bool _ignoreClosing = false;

        #endregion

        #region Constructors and Destructors

        public TaskpadPresenter(TaskpadWindow view, PomodoroController pomodoroController)
        {
            _view = view;
            this._pomodoroController = pomodoroController;
        }

        #endregion

        #region Public Methods

        public void Init()
        {
            _view.Tasks = this._pomodoroController.Tasks;
        }

        #endregion

        #region Methods

        #endregion

        public void OnClosing()
        {
            if (!_ignoreClosing)
            {
                this._pomodoroController.Tasks.Clear();
                this._pomodoroController.Tasks.AddRange(_view.Tasks);
                TaskpadClosing();
            }
        }

        public void OnTaskClick(int index)
        {
            this._pomodoroController.Tasks.Clear();
            this._pomodoroController.Tasks.AddRange(_view.Tasks);

            foreach (var task in this._pomodoroController.Tasks)
            {
                task.Active = false;
            }
            this._pomodoroController.Tasks.Skip(index).First().Active = true;
            
            TaskpadClosing();
            _ignoreClosing = true;
            _view.Close();
        }
    }
}